package com.promise.jokerdream.ui.customtask

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.ui.components.AddTaskItem
import com.promise.jokerdream.ui.components.DangerAlertDialog
import com.promise.jokerdream.ui.components.TaskEditDialog
import com.promise.jokerdream.ui.components.SingleSelectHashtagBottomSheet
import com.promise.jokerdream.ui.components.TaskNameInputDialog
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.model.configtask.PreConfigTaskMapping
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.database.entity.TaskGroupConfigEntity
import com.promise.jokerdream.database.entity.TaskConfigEntity
import com.promise.jokerdream.work.manager.CustomTaskWorkManager
import com.promise.jokerdream.R
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope

/**
 * 任务配置页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskConfigPage(
    userId: String,
    taskGroupId: String,
    onBackClick: () -> Unit,
    onNavigateToExecutionLog: () -> Unit
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    val coroutineScope = rememberCoroutineScope()
    
    // 将 String taskGroupId 转换为 Long
    val taskGroupIdLong = taskGroupId.toLongOrNull() ?: 0L
    
    // 任务组配置状态
    var taskGroupConfig by remember { mutableStateOf<TaskGroupConfigEntity?>(null) }
    
    // 任务列表状态
    var taskList by remember { mutableStateOf<List<TaskConfigEntity>>(emptyList()) }
    
    // 编辑对话框状态
    var showEditDialog by remember { mutableStateOf(false) }
    var editingTask by remember { mutableStateOf<TaskConfigEntity?>(null) }
    
    // 滑动删除状态
    var swipedTaskId by remember { mutableStateOf<String?>(null) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var taskToDelete by remember { mutableStateOf<TaskConfigEntity?>(null) }
    
    // 快捷指令选择状态
    var showQuickCommandDialog by remember { mutableStateOf(false) }
    var selectedCommand by remember { mutableStateOf("") }
    
    // 修改任务组名字状态
    var showEditGroupNameDialog by remember { mutableStateOf(false) }
    
    // 加载任务组配置和任务列表
    LaunchedEffect(userId, taskGroupIdLong) {
        val account = userDataManager.getUserAccount(userId)
        val foundTaskGroup = account?.config?.taskListConfig?.find { it.groupId == taskGroupIdLong }
        taskGroupConfig = foundTaskGroup
        
        // 从数据库加载任务列表
        if (foundTaskGroup != null) {
            val tasks = userDataManager.getTasksByGroupId(taskGroupIdLong)
            taskList = tasks
        } else {
            taskList = emptyList()
        }
    }
    
    // 保存任务列表到数据库
    fun saveTaskList(updatedTaskList: List<TaskConfigEntity>) {
        coroutineScope.launch {
            try {
                userDataManager.saveTaskList(taskGroupIdLong, updatedTaskList)
                // 重新加载任务列表
                val tasks = userDataManager.getTasksByGroupId(taskGroupIdLong)
                taskList = tasks
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    // 处理返回键
    BackHandler {
        onBackClick()
    }
    
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.PageBackground)
    ) {
        // 顶部导航栏
        AppTopBar(
            title = taskGroupConfig?.groupName ?: "任务配置",
            onBackClick = onBackClick,
            actionIcon = {
                if (taskGroupConfig != null) {
                    Button(
                        onClick = { showEditGroupNameDialog = true },
                        modifier = Modifier.height(28.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary
                        ),
                        contentPadding = PaddingValues(horizontal = AppSpacing.componentLarge)
                    ) {
                        Text(
                            text = "编辑",
                            fontSize = AppFontSizes.buttonMedium,
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
            }
        )
        
        // 内容区域
        if (taskGroupConfig == null) {
            // 加载中或未找到状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "任务组不存在",
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        } else {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                LazyColumn(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = AppSpacing.pageHorizontal),
                    verticalArrangement = Arrangement.spacedBy(0.dp),
                    contentPadding = PaddingValues(vertical = AppSpacing.pageVertical)
                ) {
                    // 任务列表
                    items(taskList) { task ->
                        ConfigTaskItemWithLine(
                            taskData = task,
                            isSwiped = swipedTaskId == task.taskId,
                            onEditClick = {
                                editingTask = task
                                showEditDialog = true
                            },
                            onSwipeStart = { swipedTaskId = task.taskId },
                            onSwipeEnd = { swipedTaskId = null },
                            onDelete = {
                                taskToDelete = task
                                showDeleteDialog = true
                            },
                            onEnabledChange = { enabled ->
                                val updatedTask = task.copy(enabled = enabled)
                                val updatedTaskList = taskList.map { 
                                    if (it.taskId == task.taskId) updatedTask else it 
                                }
                                taskList = updatedTaskList
                                saveTaskList(updatedTaskList)
                            }
                        )
                    }
                    
                    // 添加任务按钮
                    item {
                        AddTaskItem(
                            onClick = {
                                editingTask = null
                                showEditDialog = true
                            }
                        )
                    }
                }
                
                // 底部操作区域（包含快捷指令和一键执行按钮）
                BottomActionSection(
                    onOneClickExecute = {
                        // 执行当前任务组中的所有任务
                        taskGroupConfig?.let { config ->
                            val customTaskWorkManager = CustomTaskWorkManager.getInstance()
                            customTaskWorkManager.executeTaskGroup(config)
                            onNavigateToExecutionLog()
                        }
                    },
                    onQuickCommandClick = { command ->
                        selectedCommand = command
                        showQuickCommandDialog = true
                    }
                )
            }
        }
    }
    
    // 编辑对话框
    TaskEditDialog(
        show = showEditDialog,
        taskName = editingTask?.taskName ?: "",
        executionCount = editingTask?.executionCount?.toString() ?: "",
        taskLink = editingTask?.taskLink ?: "",
        onDismiss = {
            showEditDialog = false
            editingTask = null
        },
        onConfirm = { taskName, executionCount, taskLink ->
            val updatedTaskList = if (editingTask != null) {
                // 编辑现有任务
                val updatedTask = editingTask!!.copy(
                    taskName = taskName,
                    executionCount = executionCount.toIntOrNull() ?: 1,
                    taskLink = taskLink
                )
                taskList.map { if (it.taskId == editingTask!!.taskId) updatedTask else it }
            } else {
                // 新建任务
                val newTask = TaskConfigEntity(
                    id = 0, // 自增，让数据库生成
                    taskGroupId = taskGroupIdLong,
                    taskId = System.currentTimeMillis().toString(),
                    taskName = taskName,
                    executionCount = executionCount.toIntOrNull() ?: 1,
                    taskLink = taskLink,
                    enabled = true
                )
                taskList + newTask
            }
            
            // 更新本地状态
            taskList = updatedTaskList
            
            // 保存到数据库
            saveTaskList(updatedTaskList)
            
            showEditDialog = false
            editingTask = null
        }
    )
    
    // 删除确认对话框
    DangerAlertDialog(
        show = showDeleteDialog,
        title = "删除任务",
        content = "确定要删除任务 \"${taskToDelete?.taskName}\" ？",
        confirmText = "删除",
        cancelText = "取消",
        onDismiss = { 
            showDeleteDialog = false
            taskToDelete = null
        },
        onConfirm = {
            taskToDelete?.let { task ->
                // 从数据库删除任务
                userDataManager.deleteTask(task.taskId)
                
                // 重新加载任务列表
                coroutineScope.launch {
                    val tasks = userDataManager.getTasksByGroupId(taskGroupIdLong)
                    taskList = tasks
                }
                
                showDeleteDialog = false
                taskToDelete = null
                swipedTaskId = null
            }
        }
    )
    
    // 快捷指令选择对话框
    if (showQuickCommandDialog) {
        val recommendedTasks = PreConfigTaskMapping.getTasksByCommand(selectedCommand)
        
        SingleSelectHashtagBottomSheet(
            title = "选择${selectedCommand}任务",
            initialText = "", // 空字符串，不显示输入框
            recommendedTags = recommendedTasks.map { it.taskName },
            onCancel = {},
            onDismiss = {
                showQuickCommandDialog = false
                selectedCommand = ""
            },
            onComplete = { selectedTaskName ->
                // 找到对应的TaskConfig
                val selectedTask = recommendedTasks.find { it.taskName == selectedTaskName }
                selectedTask?.let { task ->
                    // 创建TaskConfigEntity
                    val newTask = TaskConfigEntity(
                        id = 0, // 自增，让数据库生成
                        taskGroupId = taskGroupIdLong,
                        taskId = "${task.id}_${System.currentTimeMillis()}", // 生成唯一ID避免重复
                        taskName = task.taskName,
                        executionCount = task.executionCount,
                        taskLink = task.taskLink,
                        enabled = task.enabled
                    )
                    val updatedTaskList = taskList + newTask
                    
                    // 更新本地状态
                    taskList = updatedTaskList
                    
                    // 保存到数据库
                    saveTaskList(updatedTaskList)
                }
                
                showQuickCommandDialog = false
                selectedCommand = ""
            }
        )
    }
    
    // 修改任务组名字对话框
    TaskNameInputDialog(
        show = showEditGroupNameDialog,
        initialText = taskGroupConfig?.groupName ?: "",
        onTaskNameEntered = { newGroupName ->
            showEditGroupNameDialog = false
            if (taskGroupConfig != null && newGroupName.isNotEmpty()) {
                // 更新任务组名字
                val updatedTaskGroupConfig = taskGroupConfig!!.copy(groupName = newGroupName)
                // 保存到数据库
                userDataManager.updateTaskGroup(userId, updatedTaskGroupConfig)
                // 更新本地状态
                taskGroupConfig = updatedTaskGroupConfig
                // 重新加载任务组列表
                val account = userDataManager.getUserAccount(userId)
                val updatedGroup = account?.config?.taskListConfig?.find { it.groupId == taskGroupIdLong }
                taskGroupConfig = updatedGroup
            }
        },
        onDismiss = { showEditGroupNameDialog = false }
    )
}

/**
 * 带连接线的任务项组件
 */
@Composable
private fun ConfigTaskItemWithLine(
    taskData: TaskConfigEntity,
    isSwiped: Boolean = false,
    onEditClick: () -> Unit,
    onSwipeStart: () -> Unit = {},
    onSwipeEnd: () -> Unit = {},
    onDelete: () -> Unit = {},
    onEnabledChange: (Boolean) -> Unit = {},
    modifier: Modifier = Modifier
) {
    Column(modifier = modifier) {
        // 任务项容器 - 支持滑动删除
        SwipeableTaskItem(
            taskData = taskData,
            isSwiped = isSwiped,
            onEditClick = onEditClick,
            onSwipeStart = onSwipeStart,
            onSwipeEnd = onSwipeEnd,
            onDelete = onDelete,
            onEnabledChange = onEnabledChange
        )
        
        // 连接线 - 紧贴上方item
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
                .height(8.dp)
        ) {
            Box(
                modifier = Modifier
                    .width(2.dp)
                    .height(8.dp)
                    .background(AppColors.Gray500)
                    .align(Alignment.Center)
            )
        }
    }
}

/**
 * 可滑动的任务项组件
 */
@Composable
private fun SwipeableTaskItem(
    taskData: TaskConfigEntity,
    isSwiped: Boolean,
    onEditClick: () -> Unit,
    onSwipeStart: () -> Unit,
    onSwipeEnd: () -> Unit,
    onDelete: () -> Unit,
    onEnabledChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    var offsetX by remember { mutableStateOf(0f) }
    val swipeThreshold = 80f
    
    // 当其他任务项开始滑动时，重置当前项的滑动状态
    LaunchedEffect(isSwiped) {
        if (!isSwiped) {
            offsetX = 0f
        }
    }
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(76.dp) // 固定高度
    ) {
        // 删除按钮背景 - 跟随手势左滑拉出
        if (offsetX < 0) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .width((-offsetX).dp)
                    .background(Color.Red)
                    .align(Alignment.CenterEnd)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .clickable { onDelete() },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_delete),
                        contentDescription = "删除任务",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
        
        // 任务项
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .offset(x = offsetX.dp)
                .background(
                    color = AppColors.CardBackground,
                    shape = RoundedCornerShape(12.dp)
                )
                .pointerInput(Unit) {
                    detectHorizontalDragGestures(
                        onDragStart = { onSwipeStart() },
                        onDragEnd = {
                            if (offsetX < -swipeThreshold/2) {
                                offsetX = -swipeThreshold
                            } else {
                                offsetX = 0f
                                onSwipeEnd()
                            }
                        }
                    ) { _, x ->
                        if (x < 0) {
                            offsetX = (offsetX + x).coerceAtLeast(-swipeThreshold)
                        } else if (offsetX < 0) {
                            offsetX = (offsetX + x).coerceAtMost(0f)
                        }
                    }
                }
                .clickable { 
                    if (offsetX == 0f) {
                        onEditClick()
                    }
                }
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp)
            ) {
                // 标题行：复选框 + 任务名称
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onEnabledChange(!taskData.enabled) },
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 启用/禁用复选框
                    RoundCheckbox(
                        checked = taskData.enabled,
                        onCheckedChange = onEnabledChange
                    )
                    
                    // 任务名称
                    Text(
                        text = taskData.taskName,
                        fontSize = AppFontSizes.body,
                        fontWeight = FontWeight.Medium,
                        color = if (taskData.enabled) AppColors.TextPrimary else AppColors.TextSecondary,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f)
                    )
                }
                
                Spacer(modifier = Modifier.height(6.dp))
                
                // 执行次数
                Text(
                    text = "执行次数：${taskData.executionCount}",
                    fontSize = AppFontSizes.mediumBody,
                    color = AppColors.TextSecondary,
                    modifier = Modifier.padding(start = 32.dp) // 与复选框对齐
                )
            }
        }
    }
}

/**
 * 底部操作区域（包含快捷指令和一键执行按钮）
 */
@Composable
private fun BottomActionSection(
    onOneClickExecute: () -> Unit,
    onQuickCommandClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shadowElevation = 8.dp
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    horizontal = AppSpacing.pageHorizontal,
                    vertical = AppSpacing.pageVertical
                )
        ) {
            // 快捷指令区域
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 12.dp)
            ) {
                // 标题
                Text(
                    text = "快捷指令",
                    fontSize = AppFontSizes.h4,
                    fontWeight = FontWeight.Medium,
                    color = AppColors.TextPrimary,
                    modifier = Modifier.padding(bottom = 6.dp)
                )
                
                // 指令列表
                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    val commands = listOf("佣兵", "奥义", "用药", "状态", "背包")
                    
                    items(commands) { command ->
                        QuickCommandItem(
                            text = command,
                            onClick = {
                                onQuickCommandClick(command)
                            }
                        )
                    }
                }
            }
            
            // 一键执行按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End
            ) {
                Button(
                    onClick = onOneClickExecute,
                    modifier = Modifier.width(120.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Text(
                        text = "一键执行",
                        fontSize = AppFontSizes.mediumBody,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }
        
        // 底部安全区域
        Spacer(
            modifier = Modifier
                .fillMaxWidth()
                .windowInsetsPadding(WindowInsets.navigationBars)
                .height(0.dp)
        )
    }
}

/**
 * 快捷指令项
 */
@Composable
private fun QuickCommandItem(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier
            .background(
                color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f),
                shape = RoundedCornerShape(8.dp)
            )
            .clickable { onClick() }
            .padding(horizontal = 8.dp, vertical = 2.dp)
    ) {
        Text(
            text = text,
            fontSize = AppFontSizes.mediumBody,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.primary
        )
    }
}
